package com.example.View;

import com.example.AlertHelper;
import com.example.PO.Customer;
import com.example.Service.CustomerService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.util.List;

public class CustomerView {
    private CustomerService customerService = new CustomerService();
    private TableView<Customer> tableView;
    private ObservableList<Customer> customerList;

    public CustomerView() {
        // 创建表格视图
        tableView = new TableView<>();
        customerList = FXCollections.observableArrayList(customerService.getAllCustomers());
        tableView.setItems(customerList);

        // 定义表格列
        TableColumn<Customer, Integer> idColumn = new TableColumn<>("客户编号");
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));

        TableColumn<Customer, String> nameColumn = new TableColumn<>("客户姓名");
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));

        TableColumn<Customer, String> phoneColumn = new TableColumn<>("客户电话");
        phoneColumn.setCellValueFactory(new PropertyValueFactory<>("phone"));

        TableColumn<Customer, String> addressColumn = new TableColumn<>("客户地址");
        addressColumn.setCellValueFactory(new PropertyValueFactory<>("address"));

        tableView.getColumns().addAll(idColumn, nameColumn, phoneColumn, addressColumn);

        // 创建操作按钮
        Button addButton = new Button("添加客户");
        Button editButton = new Button("编辑客户");
        Button deleteButton = new Button("删除客户");
        Button refreshButton = new Button("刷新");

        // 按钮事件处理
        addButton.setOnAction(e -> showAddCustomerDialog());
        editButton.setOnAction(e -> showEditCustomerDialog());
        deleteButton.setOnAction(e -> deleteSelectedCustomer());
        refreshButton.setOnAction(e -> refreshTable());

        // 按钮布局
        HBox buttonBox = new HBox(10);
        buttonBox.getChildren().addAll(addButton, editButton, deleteButton, refreshButton);

        // 搜索框
        TextField searchField = new TextField();
        searchField.setPromptText("请输入搜索内容");
        searchField.textProperty().addListener((observable, oldValue, newValue) -> filterTable(newValue));

        // 主布局
        VBox view = new VBox(20);
        view.getChildren().addAll(searchField, buttonBox, tableView);
    }

    public VBox getView() {
        VBox view = new VBox(20);
        TextField searchField = new TextField();
        searchField.setPromptText("请输入搜索内容");
        searchField.textProperty().addListener((observable, oldValue, newValue) -> filterTable(newValue));

        Button addButton = new Button("添加客户");
        Button editButton = new Button("编辑客户");
        Button deleteButton = new Button("删除客户");
        Button refreshButton = new Button("刷新");

        addButton.setOnAction(e -> showAddCustomerDialog());
        editButton.setOnAction(e -> showEditCustomerDialog());
        deleteButton.setOnAction(e -> deleteSelectedCustomer());
        refreshButton.setOnAction(e -> refreshTable());

        HBox buttonBox = new HBox(10);
        buttonBox.getChildren().addAll(addButton, editButton, deleteButton, refreshButton);

        view.getChildren().addAll(searchField, buttonBox, tableView);
        return view;
    }

    private void showAddCustomerDialog() {
        Dialog<Customer> dialog = new Dialog<>();
        dialog.setTitle("添加客户");
        dialog.setHeaderText("请输入客户信息");

        // 设置对话框按钮
        ButtonType addButtonType = new ButtonType("添加", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(addButtonType, ButtonType.CANCEL);

        // 创建输入字段
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);

        TextField nameField = new TextField();
        nameField.setPromptText("客户姓名");
        TextField phoneField = new TextField();
        phoneField.setPromptText("客户电话");
        TextField addressField = new TextField();
        addressField.setPromptText("客户地址");

        grid.add(new Label("客户姓名:"), 0, 0);
        grid.add(nameField, 1, 0);
        grid.add(new Label("客户电话:"), 0, 1);
        grid.add(phoneField, 1, 1);
        grid.add(new Label("客户地址:"), 0, 2);
        grid.add(addressField, 1, 2);

        dialog.getDialogPane().setContent(grid);

        // 转换结果
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == addButtonType) {
                int newId = customerList.size() + 1;
                return new Customer(newId, nameField.getText(), phoneField.getText(), addressField.getText());
            }
            return null;
        });

        // 处理结果
        dialog.showAndWait().ifPresent(customer -> {
            customerService.addCustomer(customer);
            customerList.add(customer);
        });
    }

    private void showEditCustomerDialog() {
        Customer selectedCustomer = tableView.getSelectionModel().getSelectedItem();
        if (selectedCustomer != null) {
            Dialog<Customer> dialog = new Dialog<>();
            dialog.setTitle("编辑客户");
            dialog.setHeaderText("请修改客户信息");

            // 设置对话框按钮
            ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
            dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

            // 创建输入字段
            GridPane grid = new GridPane();
            grid.setHgap(10);
            grid.setVgap(10);

            TextField nameField = new TextField(selectedCustomer.getName());
            nameField.setPromptText("客户姓名");
            TextField phoneField = new TextField(selectedCustomer.getPhone());
            phoneField.setPromptText("客户电话");
            TextField addressField = new TextField(selectedCustomer.getAddress());
            addressField.setPromptText("客户地址");

            grid.add(new Label("客户姓名:"), 0, 0);
            grid.add(nameField, 1, 0);
            grid.add(new Label("客户电话:"), 0, 1);
            grid.add(phoneField, 1, 1);
            grid.add(new Label("客户地址:"), 0, 2);
            grid.add(addressField, 1, 2);

            dialog.getDialogPane().setContent(grid);

            // 转换结果
            dialog.setResultConverter(dialogButton -> {
                if (dialogButton == saveButtonType) {
                    selectedCustomer.setName(nameField.getText());
                    selectedCustomer.setPhone(phoneField.getText());
                    selectedCustomer.setAddress(addressField.getText());
                    return selectedCustomer;
                }
                return null;
            });

            // 处理结果
            dialog.showAndWait().ifPresent(customer -> {
                customerService.updateCustomer(customer);
                refreshTable();
            });
        }
    }

    private void deleteSelectedCustomer() {
        Customer selectedCustomer = tableView.getSelectionModel().getSelectedItem();
        if (selectedCustomer != null) {
            if (AlertHelper.showConfirmationDialog("确认删除", "确定要删除该客户信息吗？")) {
                customerService.deleteCustomer(selectedCustomer.getId());
                customerList.remove(selectedCustomer);
            }
        }
    }

    private void refreshTable() {
        customerList.clear();
        customerList.addAll(customerService.getAllCustomers());
    }

    private void filterTable(String keyword) {
        List<Customer> allCustomers = customerService.getAllCustomers();
        customerList.clear();
        for (Customer customer : allCustomers) {
            if (customer.getName().contains(keyword) ||
                    customer.getPhone().contains(keyword) ||
                    customer.getAddress().contains(keyword)) {
                customerList.add(customer);
            }
        }
    }
}